package com.juku2024.juku.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.R
import com.juku2024.juku.adapter.CategorySearchTagListAdapter
import com.juku2024.juku.callback.OnSearchKeySelectedCallback
import com.juku2024.juku.model.CategorySearchModel
import com.juku2024.juku.model.CategorySearchTagModel
import kotlin.collections.ArrayList


class CategorySearchTagView(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {

    var callback: OnSearchKeySelectedCallback? = null
    private val keyRecycler: RecyclerView
    init {
        val rootView = LayoutInflater.from(context).inflate(R.layout.view_category_search_tag, this, true)
        keyRecycler = rootView.findViewById(R.id.keyRecycler)
        keyRecycler.layoutManager = LinearLayoutManager(context)
        keyRecycler.setHasFixedSize(true)
    }

    fun init(category: CategorySearchModel?) {
        if (category == null) return
        visibility = View.VISIBLE
        val list: MutableList<ArrayList<CategorySearchTagModel>> = ArrayList()

        if (category.tags?.isNotEmpty() == true) {
            val tagsList = category.tags!!.toMutableList() as ArrayList
            list.add(tagsList)
        }
        if (category.years?.isNotEmpty() == true) {
            val yearsList = category.years!!.toMutableList() as ArrayList
            list.add(yearsList)
        }

        val adapter = CategorySearchTagListAdapter(list, object : OnCategoryGTagSelectedCallback {
            override fun onSearchKeySelected(position: Int, keyModel: CategorySearchTagModel?) {
                val classes = category.classes?.firstOrNull { it.isSelected }?.id ?: 0
                val tags = list.getOrNull(0)?.firstOrNull { it.isSelected }?.id ?: 0
                val years = list.getOrNull(1)?.firstOrNull { it.isSelected }?.id ?: 0
                callback?.onSearchKeySelected(classes, tags, years, keyModel)
            }
        })

        keyRecycler.adapter = adapter
    }

    fun release(){
        visibility = View.GONE
        (keyRecycler.adapter as CategorySearchTagListAdapter?)?.setList(ArrayList())
        keyRecycler.adapter = null
    }

    interface OnCategoryGTagSelectedCallback {
        fun onSearchKeySelected(position: Int, keyModel: CategorySearchTagModel?)
    }


}